<?php

function doGzip($content, $sHeader, $iLevel = 9)
{	
	$expiresOffset = 3600 * 24 * 10;
	$supportsGzip = false;

	if ($sHeader != 'no_header')
	{
		header("Content-type: text/" . $sHeader);
		header("Vary: Accept-Encoding");  
		header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expiresOffset) . " GMT");
	}
	
	if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))
	{
		$encodings = explode(',', strtolower(preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_ENCODING'])));
	}
	
	if (!isset($encodings))
	{
		if ($sHeader != 'no_header')
		{
			echo $content;
			exit;
		}
		else
		{
			return $content;
		}		
	}
	
	if ((in_array('gzip', $encodings) || in_array('x-gzip', $encodings) || isset($_SERVER['---------------'])) && function_exists('ob_gzhandler') && !ini_get('zlib.output_compression') && !headers_sent()) 
	{
		$enc = in_array('x-gzip', $encodings) ? "x-gzip" : "gzip";
		$supportsGzip = true;
	}

	if ($supportsGzip)
	{
		if (function_exists('gzencode'))
		{			
			if (defined('GZIP_DO_CACHE'))
			{
				$sCacheGz = GZIP_DO_CACHE . md5($content) . '.gz';
				if (!file_exists($sCacheGz))
				{
					$sGzipContent = gzencode($content, $iLevel, FORCE_GZIP);	
					$hFile = fopen($sCacheGz, 'w');
					fwrite($hFile, $sGzipContent);
					fclose($hFile);
				}
				else
				{
					$sGzipContent = file_get_contents($sCacheGz);
				}
			}
			else
			{			
				$sGzipContent = gzencode($content, $iLevel, FORCE_GZIP);
			}
		}
		else
		{
			if (function_exists('gzcompress') && function_exists('crc32'))
			{		
				$size = strlen($content);
				$crc = crc32($content);
				$sGzipContent = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff";
				$sGzipContent .= substr(gzcompress($content, $iLevel), 2, -4);
				$sGzipContent .= pack('V', $crc);
				$sGzipContent .= pack('V', $size);		
			}
		}
		
		if (isset($sGzipContent))
		{
			header("Content-Encoding: " . $enc);
		}
	}

	if ($sHeader != 'no_header')
	{
		echo (isset($sGzipContent) ? $sGzipContent : $content);
		exit;
	}
	else
	{
		return (isset($sGzipContent) ? $sGzipContent : $content);
	}
}	

?>